package com.etime.dao.impl;

import com.etime.dao.StudentDao;
import com.etime.entity.Student;
import com.etime.util.C3P0Util;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.util.List;

public class StudentDaoImpl implements StudentDao {
  QueryRunner queryRunner = new QueryRunner(C3P0Util.getDataSource());
  @Override
  public Student login(String username, String password) {
    Student query = null;
    try {
      String sql = "select * from student where name = ? and password = ?";
      BeanHandler<Student> beanHandler = new BeanHandler<>(Student.class);
      query = queryRunner.query(sql, beanHandler,username,password);
    }
    catch (Exception e){
      System.out.println(e);
    }
    return query;
  }

  @Override
  public int delete(int id) {
    int i = -1;
    String sql = "delete from student where id=?";
    try {
      i = queryRunner.update(sql, id);
    }
    catch (Exception e){
      System.out.println(e);
    }
    return i;
  }

  @Override
  public int update(String password,int id) {
    String sql = "update student set password=? where id=?";
    int value = -1;
    try {
      value = queryRunner.update(sql, password,id);
    }
    catch (Exception e){
      System.out.println(e);
    }
    return value;
  }

  @Override
  public int insert(Student student) {
    int value = -1;
    String sql = "insert into student(name,password,photo) values(?,?,?)";
    try {
      value = queryRunner.update(sql, student.getName(), student.getPassword(),student.getPhoto());
    }
    catch (Exception e){
      System.out.println(e);
    }
    return value;
  }

  @Override
  public List<Student> select(Student student) {
    List<Student> query = null;
    String sql = "select * from student where name = ? and password = ?";
    BeanListHandler<Student> beanListHandler = new BeanListHandler<>(Student.class);
    try {
      query = queryRunner.query(sql, beanListHandler, student.getName(), student.getPassword());
    }
    catch (Exception e){
      System.out.println(e);
    }
    return query;
  }

  @Override
  public List<Student> limitSelect(int index,int rows) {
    List<Student> value = null;
    String sql = "select * from student limit ?,?";
    BeanListHandler<Student> beanListHandler = new BeanListHandler<>(Student.class);
    try {
      value = queryRunner.query(sql, beanListHandler,index,rows);
    }
    catch (Exception e){
      System.out.println(e);
    }
    return value;
  }
}
